package com.xhorse.lockplatform.comm.util;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.assertj.core.util.Lists;
import org.assertj.core.util.Strings;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 自定义用于Sql的方法表
 *
 * @author Tom
 */
public final class SqlFunc {
    private static final SqlFunc FUNC = new SqlFunc();

    private SqlFunc() {
    }

    public static final SqlFunc get() {
        return FUNC;
    }

    public static List<String> dateBetween(String startDate, String endDate) throws ParseException {
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(DateUtils.parseDate(startDate, "yyyy-MM-dd"));
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(DateUtils.parseDate(endDate, "yyyy-MM-dd"));
        if (startCal.after(endCal)) {
            return Lists.newArrayList(startDate);
        }
        List<String> dates = new ArrayList<>();
        while (startCal.compareTo(endCal) <= 0) {
            dates.add(DateFormatUtils.format(startCal, "yyyy-MM-dd"));
            startCal.add(Calendar.DATE, 1);
        }
        return dates;
    }

    public static String searchAny(String value) {
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return String.format("%%%s%%", value);
    }

    public static String inList(List<String> datas) {
        if (datas == null || datas.isEmpty()) {
            return "";
        }
        StringBuilder sql = new StringBuilder();
        sql.append("(");
        for (String data : datas) {
            sql.append("'").append(data).append("',");
        }
        sql.setCharAt(sql.length() - 1, ')');
        return sql.toString();
    }

    public boolean lt(Number value, Number target) {
        return value != null && value.doubleValue() < target.doubleValue();
    }

    public boolean gt0(Number value) {
        return gt(value, 0);
    }

    public boolean gtM1(Number value) {
        return gt(value, -1);
    }

    public boolean gt(Number value, Number target) {
        return value != null && value.doubleValue() > target.doubleValue();
    }

    public boolean notNull(Object value) {
        return value != null;
    }

    public boolean notEmpty(Object value) {
        return value != null && (!(value instanceof String) || !Strings.isNullOrEmpty((String) value));
    }

    public Number getM1() {
        return -1;
    }
}
